package priv.lhy.ecm.manager.controller;

import org.springframework.web.bind.annotation.RequestBody;
import priv.lhy.common.abs.AbstractCoreRequest;
import priv.lhy.common.abs.AbstractResponse;
import priv.lhy.common.constants.MethodCode;
import priv.lhy.common.controller.AbsBasicController;
import priv.lhy.ecm.basic.constants.BasicResponseCode;
import priv.lhy.ecm.basic.exception.BasicException;
import priv.lhy.ecm.basic.service.IService;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * author: lihy
 * date: 2019/5/8 9:35
 * description:抽象controller方法，封装单表的add和modify方法
 */
public abstract class AbsController<T> extends AbsBasicController {

    private IService service;

    /**
     * 由子类提供service
     * @return
     */
    public abstract IService getService();

    public Map<String, Object> add(@RequestBody T t, HttpServletRequest request) {
        return addOrModify(t, request, MethodCode.INSERT);
    }

    public Map<String, Object> modify(@RequestBody T t, HttpServletRequest request) {
        return addOrModify(t, request, MethodCode.MODIFY);
    }

    private Map<String, Object> addOrModify(T t, HttpServletRequest request, MethodCode code) {
        this.service = getService();
        AbstractResponse response = new AbstractResponse();
        AbstractCoreRequest entityRequest = new AbstractCoreRequest();
        entityRequest = (AbstractCoreRequest)assemblyRequest(entityRequest, request);
        entityRequest.setT(t);
        switch (code) {
            case INSERT:
                response = service.add(response, entityRequest);
                break;
            case MODIFY:
                response = service.modify(response, entityRequest);
                break;
            default:
                throw new BasicException(BasicResponseCode.SYSTEM_BUSY.getCode(),
                        BasicResponseCode.SYSTEM_BUSY.getMsg(), entityRequest);
        }
        return assemblyResult(response);
    }


}
